import { defineStore } from 'pinia'
import { ref } from 'vue'
import { 
  getUserAddresses, 
  getDefaultAddress, 
  getAddressById, 
  createAddress, 
  updateAddress, 
  deleteAddress, 
  setDefaultAddress,
  type Address 
} from '@/api/address'

export const useAddressStore = defineStore('address', () => {
  const addresses = ref<Address[]>([])
  const defaultAddress = ref<Address | null>(null)
  const loading = ref(false)

  // 获取用户的所有地址
  const fetchAddresses = async (userId: number) => {
    try {
      loading.value = true
      const response = await getUserAddresses(userId)
      console.log('地址列表API响应:', response)
      if (response.data && response.data.success && response.data.addresses) {
        addresses.value = response.data.addresses
      }
      return response.data
    } catch (error: any) {
      console.error('获取地址列表失败:', error)
      return { success: false, message: error.response?.data?.message || '获取地址列表失败' }
    } finally {
      loading.value = false
    }
  }

  // 获取用户的默认地址
  const fetchDefaultAddress = async (userId: number) => {
    try {
      loading.value = true
      const response = await getDefaultAddress(userId)
      console.log('默认地址API响应:', response)
      if (response.data && response.data.success && response.data.address) {
        defaultAddress.value = response.data.address
      }
      return response.data
    } catch (error: any) {
      console.error('获取默认地址失败:', error)
      return { success: false, message: error.response?.data?.message || '获取默认地址失败' }
    } finally {
      loading.value = false
    }
  }

  // 根据ID获取地址详情
  const fetchAddressById = async (userId: number, addressId: number) => {
    try {
      loading.value = true
      const response = await getAddressById(userId, addressId)
      if (response.data && response.data.success) {
        return response.data.address
      }
      return null
    } catch (error: any) {
      console.error('获取地址详情失败:', error)
      return null
    } finally {
      loading.value = false
    }
  }

  // 创建新地址
  const addAddress = async (userId: number, addressData: Omit<Address, 'id' | 'userId' | 'createdAt' | 'updatedAt'>) => {
    try {
      loading.value = true
      const response = await createAddress(userId, addressData)
      if (response.data && response.data.success) {
        // 重新获取地址列表
        await fetchAddresses(userId)
        // 如果设置为默认地址，重新获取默认地址
        if (addressData.isDefault) {
          await fetchDefaultAddress(userId)
        }
      }
      return response.data
    } catch (error: any) {
      console.error('创建地址失败:', error)
      return { success: false, message: error.response?.data?.message || '创建地址失败' }
    } finally {
      loading.value = false
    }
  }

  // 更新地址
  const editAddress = async (userId: number, addressId: number, addressData: Partial<Address>) => {
    try {
      loading.value = true
      const response = await updateAddress(userId, addressId, addressData)
      if (response.data && response.data.success) {
        // 重新获取地址列表
        await fetchAddresses(userId)
        // 如果修改了默认地址设置，重新获取默认地址
        if (addressData.isDefault !== undefined) {
          await fetchDefaultAddress(userId)
        }
      }
      return response.data
    } catch (error: any) {
      console.error('更新地址失败:', error)
      return { success: false, message: error.response?.data?.message || '更新地址失败' }
    } finally {
      loading.value = false
    }
  }

  // 删除地址
  const removeAddress = async (userId: number, addressId: number) => {
    try {
      loading.value = true
      const response = await deleteAddress(userId, addressId)
      if (response.data && response.data.success) {
        // 重新获取地址列表
        await fetchAddresses(userId)
        // 重新获取默认地址
        await fetchDefaultAddress(userId)
      }
      return response.data
    } catch (error: any) {
      console.error('删除地址失败:', error)
      return { success: false, message: error.response?.data?.message || '删除地址失败' }
    } finally {
      loading.value = false
    }
  }

  // 设置默认地址
  const setDefault = async (userId: number, addressId: number) => {
    try {
      loading.value = true
      const response = await setDefaultAddress(userId, addressId)
      if (response.data && response.data.success) {
        // 重新获取地址列表
        await fetchAddresses(userId)
        // 重新获取默认地址
        await fetchDefaultAddress(userId)
      }
      return response.data
    } catch (error: any) {
      console.error('设置默认地址失败:', error)
      return { success: false, message: error.response?.data?.message || '设置默认地址失败' }
    } finally {
      loading.value = false
    }
  }

  // 清空状态
  const clearAddresses = () => {
    addresses.value = []
    defaultAddress.value = null
  }

  return {
    addresses,
    defaultAddress,
    loading,
    fetchAddresses,
    fetchDefaultAddress,
    fetchAddressById,
    addAddress,
    editAddress,
    removeAddress,
    setDefault,
    clearAddresses
  }
}) 